import { loginByUsername, logout, getUserInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import tagsView from './tagsView'
const user = {
  state: {
    id:'',
    status: '',
    token: getToken(),
    name: '',
    department: '',
    isAdmin:false,
    avatar: '',
    username: '',
    roles: [],
  },

  mutations: {
      SET_TOKEN: (state, token) => {
        state.token = token
      },
      SET_SETTING: (state, setting) => {
        state.setting = setting
      },
      SET_STATUS: (state, status) => {
        state.status = status
      },
      SET_ID: (state, id) => {
        state.id = id
      },
      SET_USERNAME: (state, username) => {
          state.username = username
          sessionStorage.setItem("username",username)
      },
      SET_NAME: (state, name) => {
        state.name = name
          sessionStorage.setItem("name",name)
      },
      SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
          sessionStorage.setItem("avatar",avatar)
      },
      SET_DEPARTMENT: (state, department) => {
        state.department = department
          sessionStorage.setItem("department",department)
      },
      SET_ISADMIN: (state, isAdmin) => {
        state.isAdmin = isAdmin
          sessionStorage.setItem("isAdmin",isAdmin)
      },
      SET_ROLES: (state, roles) => {
        state.roles = roles
          sessionStorage.setItem("roles",roles)
      },
      REFRESH_PAGE:(state) => {
          state.roles  = sessionStorage.getItem("roles") || []
          state.name  = sessionStorage.getItem("name") || ''
          state.username  = sessionStorage.getItem("username") || ''
      },
  },

  actions: {
    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password).then(response => {
          const resp = response
          commit('SET_TOKEN', resp.data.token)
          setToken(resp.data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
          getUserInfo(state.token).then(response => {
              if (!response) { // 由于mockjs 不支持自定义状态码只能这样hack
                  reject('error')
              }
              // if (resp.data.roles && resp.data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              //   commit('SET_ROLES', resp.data.roles)
              // } else {
              //   reject('getInfo: roles must be a non-null array !')
              // }
            console.log("adminuser==>",response.data.adminUser)
              commit('SET_ROLES', response.data.adminUser.userType);
              commit('SET_ID', response.data.adminUser.id);
              commit('SET_DEPARTMENT', response.data.adminUser.departName);
              commit('SET_ISADMIN', response.data.adminUser.isAdmin);
              commit('SET_USERNAME', response.data.adminUser.username);
              commit('SET_NAME', response.data.adminUser.name);
              resolve(response)
          }).catch(error => {
              reject(error)
          })
      })
    },
    // 获取用户信息
    RefreshPage({ commit, state }) {
      return new Promise((resolve, reject) => {
          // commit('REFRESH_PAGE');
          resolve(state.roles.length===0)
      })
    },
    // 第三方验证登录
    // LoginByThirdparty({ commit, state }, code) {
    //   return new Promise((resolve, reject) => {
    //     commit('SET_CODE', code)
    //     loginByThirdparty(state.status, state.email, state.code).then(response => {
    //       commit('SET_TOKEN', response.data.token)
    //       setToken(response.data.token)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
          commit('SET_TOKEN', '');
          commit('SET_USERNAME', '');
          commit('SET_NAME', '');
          commit('SET_ROLES',[]);
          tagsView.state.cachedViews = []
          tagsView.state.visitedViews = []
          removeToken()
          resolve()
      })
    },

    // 动态修改权限
    ChangeRoles({ commit, dispatch }, role) {
      return new Promise(resolve => {
        commit('SET_TOKEN', role)
        setToken(role)
        getUserInfo(role).then(response => {
          const data = response
          commit('SET_ROLES', data.roles)
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          dispatch('GenerateRoutes', data) // 动态修改权限后 重绘侧边菜单
          resolve()
        })
      })
    }
  }
}

export default user
